package br.com.loja.view.swing.form;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import br.com.loja.model.entity.ObservableEntity;
import br.com.loja.mvp.model.IModel;
import br.com.loja.mvp.presenter.IEntityPresenter;
import br.com.loja.util.reflection.ReflectionUtil;

/**
 * @brief Classe FormEntityFactory
 * @author David Luiz
 * @date 05/12/2014
 */
public class FormEntityFactory {

    public FormEntityFactory() {
    }

    public static <T extends ObservableEntity & IModel<T>> IFormEntity<T> getFormEntity(IEntityPresenter<T> presenter) {

        if (presenter == null) {
            throw new IllegalArgumentException("presenter is null");
        }

        IFormEntity<T> formEntity = null;

        List<Class<?>> classEntity = ReflectionUtil.getAllClassByAnnotation(FormEntity.class);
        Class<?> classFormEntity = null;

        for (Class<?> clazz : classEntity) {

            String nameClassEntity = clazz.getAnnotation(FormEntity.class).value().getName();
            String nameClassModel = presenter.getClassModel().getName();

            if (nameClassEntity.equals(nameClassModel)) {
                classFormEntity = clazz;
            }
        }

        try {

            if (classFormEntity == null) {
                throw new ClassNotFoundException("form entity not found in " + classEntity.size() + " classes");
            }

            Constructor<?> constructor = classFormEntity.getConstructor(IEntityPresenter.class);
            formEntity = (IFormEntity<T>) constructor.newInstance(presenter);

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            //implementar log
            System.err.println(e.getMessage());
            e.printStackTrace();
        }

        return formEntity;

    }

}
